package com.zxq.common.middleware.id;

import com.zxq.common.middleware.DistributedID;
import com.zxq.common.middleware.emuns.RedisCategory;
import com.zxq.common.middleware.gateway.RedisGateway;
import com.zxq.common.utils.internal.id.Snowflake;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;


/**
 * 不要直接实例化，使用工厂类实例化
 */
@Slf4j
@Component
public class RedisID implements DistributedID {

    private Snowflake snowflake;
    private final String WORKER_ID = "WORKER_ID";
    private final String DATA_CENTER_ID = "DATA_CENTER_ID";

    @Resource
    private RedisGateway redisGateway;

    @PostConstruct
    public void init() {

        long workerId = (long) (Math.random() * 1000);
        long dataCenterId = (long) (Math.random() * 1000);
        log.info("LOCAL {}:{}, {}:{}", WORKER_ID, workerId, DATA_CENTER_ID, dataCenterId);

        try {
            workerId = redisGateway.incr(RedisCategory.ID, WORKER_ID);
            if (workerId >= 31) {
                dataCenterId = redisGateway.incr(RedisCategory.ID, DATA_CENTER_ID);
                workerId = 0;
            } else {
                dataCenterId = Long.parseLong(StringUtils.defaultIfEmpty(redisGateway.get(RedisCategory.ID, DATA_CENTER_ID), "0"));
            }
            if (dataCenterId >= 31) {
                throw new Exception("dataCenterId超过31，redisID有重复风险");
            }
            log.info("REDIS {}:{}, {}}:{}", WORKER_ID, workerId, DATA_CENTER_ID, dataCenterId);
        } catch (Exception e) {
            log.error("redisID初始化警告，可以继续使用，但有重复风险", e);

        }
        // 可以支撑32*32台机器生成ID不重复
        snowflake = new Snowflake(workerId % 32 , dataCenterId % 32, true);
    }

    /**
     * 生成ID
     *
     * @return
     */
    @Override
    public Long nextId() {
        return snowflake.nextId();
    }

}
